package codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import java.util.Map;
import marshall.MarshallingEncoder;
import protocol.NettyMessage;

/**
 * 消息编码
 */
public final class NettyMessageEncoder extends MessageToByteEncoder<NettyMessage> {

    private MarshallingEncoder marshallingEncoder;

    public NettyMessageEncoder() throws Exception {
        marshallingEncoder = new MarshallingEncoder();
    }

    protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf sendBuf) throws Exception {
        System.out.println("开始编码"+System.currentTimeMillis());
        if (msg == null || msg.getHeader() == null){
            throw new Exception("编码消息为空");
        }
        sendBuf.writeInt((msg.getHeader().getCrcCode()));
        sendBuf.writeInt((msg.getHeader().getLength()));
        sendBuf.writeLong((msg.getHeader().getSessionID()));
        sendBuf.writeByte((msg.getHeader().getType()));
        sendBuf.writeByte((msg.getHeader().getPriority()));
        //扩展头长度
        sendBuf.writeInt((msg.getHeader().getAttachment().size()));

        String key = null;
        byte[] keyArry = null;
        Object value = null;
        for (Map.Entry<String,Object> param : msg.getHeader().getAttachment().entrySet()){
            key = param.getKey();
            keyArry = key.getBytes("UTF-8");
            sendBuf.writeInt(keyArry.length);
            sendBuf.writeBytes(keyArry);
            value = param.getValue();
            marshallingEncoder.encode(value,sendBuf);
        }
        key = null;
        keyArry = null;
        value = null;
        if (msg.getBody() != null){
            marshallingEncoder.encode(msg.getBody(),sendBuf);
        }else {
            sendBuf.writeByte(0);
        }
        sendBuf.setInt(4,sendBuf.readableBytes() - 8);
        System.out.println("编码完成");
    }

}
